# 封装，base_page.py的基本方法，初始化driver
#find,find_and_click,swip_find，find_and_sendkeys
import logging

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException


class BasePage:
    def __init__(self,driver:WebDriver = None):
        self.driver = driver

    def find(self,by,value):
        logging.info("find")
        logging.info(by)
        logging.info(value)
        #查找
        return self.driver.find_element(by,value)

    def find_and_click(self,by,value):
        logging.info("find_and_click")
        #查找之后点击
        self.find(by,value).click()

    def find_and_sendkeys(self,by,value,text):
        logging.info("find_and_sendkeys")
        logging.info(by)
        logging.info(value)
        logging.info(text)
        #查找之后输入内容
        self.find(by,value).send_keys(text)

    def get_toast_text(self):
        #获取 toast 文本
        result = self.find(MobileBy.XPATH, "//*[@class='android.widget.Toast']").get_attribute("text")
        return result
    def back(self,num = 5):
        for i in range(num):
            self.driver.back()

    def swipe_find(self,text,number=5):
        # 设置一个最大的查找次数
        for i in range(number):
            if i == number - 1:
                raise NoSuchElementException(f"找了{number-1}次，未找到")
            # 方法一：不要让find_element抛异常，在except中捕获异常，实现滑动操作
            try:
                # element = self.driver.find_element(MobileBy.XPATH,"//*[@text='添加成员']")
                element = self.driver.find_element(MobileBy.XPATH,f"//*[@text='{text}']")
                return element
            except:
                print("未找到")
                # 如果未找到这个元素，捕获这个异常，并且滑动一屏
                # 滑动
                size = self.driver.get_window_size()
                width = size.get('width')
                height = size.get('height')
                x = width/2
                y_start = height * 0.8
                y_end = height*0.3
                duration = 2000
                self.driver.swipe(x,y_start,x,y_end,duration)
            # 方法二：通过find_elements返回元素的列表
            # elements = self.driver.find_elements(MobileBy.XPATH,f"//*[@text='{text}']")
            # 判断列表的长度是否为0，如果没0，说明没有知道，否则说明找到了

